package com.tfos.study.mvc.web.data.binder.controller;

import com.tfos.study.mvc.web.data.binder.entity.Organization;
import com.tfos.study.mvc.web.data.binder.validator.EmailValidator;
import com.tfos.study.mvc.web.data.binder.validator.PhoneValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 类功能说明：WebDataBinder处理请求参数的绑定控制器 <br/>
 * 公司名称：TF（腾飞）开源 <br/>
 * 作者：luorongxi <br/>
 */
@Slf4j
@RestController
public class TestWebDataBinderController {

    @Autowired
    private PhoneValidator phoneValidator;

    @Autowired
    private EmailValidator emailValidator;

    /**
     * 接收参数,自定义编辑器
     */
    @InitBinder
    public void dataBinding(WebDataBinder binder) {
        binder.addValidators(phoneValidator, emailValidator);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //setLenient用于设置Calendar是否宽松解析字符串，如果为false，则严格解析；默认为true，宽松解析
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, "editTime", new CustomDateEditor(dateFormat, true));
    }

    @ResponseBody
    @PostMapping("/webdatabinder")
    public String createUser(@RequestBody @Valid Organization org, BindingResult result) {
        if (result.hasErrors()) {
            return result.getFieldError().getDefaultMessage();
        }
        return org.toString();
    }

}
